<?php
namespace app\api\controller;

use app\api\extend\Common;
use think\facade\Db;
/**
 * 用户控制器
 */
class HomeMuser extends Common {
    /**
     * 注册
     * @return array|\think\response\Json
     */
	public function register() {
        // 验证用户注册信息
        $res = $this->check_params();
        if (!empty($res)) {
           return $this->return_msg(400,$res); 
        }
        $data=[
            'account' => $this->params['account'],
            'password' => $this->encipher($this->params['password']),
            'user_type' => $this->params['user_type'],
            'name' => $this->generateRandomUsername(),
            'avatar_image' => 'http://192.168.50.40/smart_elderly_care_api/public/static/moren.jpg',
            'exchan_coin' => 10000
        ];
       
        $res = $this->model->register($data);
        if (!$res){
            return $this->return_msg(400,$this->getConst(false));
        }
        return $this->return_msg(200,$this->getConst());
	}
    /**
     * 登录
     * @return array|\think\response\Json
     */
	public function login() {
        // 验证用户登录信息
        $res = $this->check_params();
        if (!empty($res)) {
           return $this->return_msg(400,$res); 
        }
        $data=[
            'account' => $this->params['account'],
            'password' => $this->encipher($this->params['password']),
            'user_type' => $this->params['user_type'],
        ];
        $res = $this->model->login($data);
        if (!$res){
            return $this->return_msg(400,$this->getConst(false));
        }
        //生成token
        $token = $this->generateToken(['userId'=>$res['id'],'user_type'=>$res['user_type']],$this->key);
        return $this->return_msg(200,$this->getConst(),['token'=>$token,'ip'=>$this->request->ip()],false);
	}
    /**
     * 获取用户信息
     */
    public function info() {
        $res = $this->model->info($this->request->auth['userId']);
        if (!$res){
            return $this->return_msg(400,'获取用户信息失败');
        }
        return $this->return_msg(200,'获取用户信息成功',$res);
    }

     /**
     * 获取用户信息
     */
    public function friendInfo() {
        $id = $this->params["id"]??0;
        $res = Db::name("home_muser")->where("id",$id)->find();
        if (!$res){
            return $this->return_msg(400,'获取用户信息失败');
        }
        return $this->return_msg(200,'获取用户信息成功',$res);
    }

     /**
     * 修改取用户信息
     */
    public function reset() {
        $res = $this->model->reset($this->request->auth['userId'],$this->params);
        if (!$res){
            return $this->return_msg(400,'修改用户信息失败');
        }
        return $this->return_msg(200,'修改用户信息成功');
    }

    /**
     * 获取用户列表
     */
    public function list() {
        $data = $this->params['word']??'';
        $res = $this->model->list($data);
        return $this->return_msg(200,'获取成功',$res->toArray());
    }

}
